package img_uploader

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

// 创建 multipart form 并添加文件和表单字段
func createMultipartFormData(file *os.File, fieldName string) (*bytes.Buffer, string, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	defer writer.Close()

	// 添加文件到 multipart form
	part, err := writer.CreateFormFile(fieldName, filepath.Base(file.Name()))
	if err != nil {
		return nil, "", err
	}
	_, err = io.Copy(part, file)
	if err != nil {
		return nil, "", err
	}

	return body, writer.FormDataContentType(), nil
}

func asJson(resp *http.Response) (map[string]interface{}, error) {
	respBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	var result map[string]interface{}
	err = json.Unmarshal(respBytes, &result)
	if err != nil {
		return nil, err
	}
	return result, nil
}

func getStringInJson(json *map[string]interface{}, path string) (string, error) {
	resPaths := strings.Split(path, ".")
	tmp := *json
	for i := 0; i < len(resPaths)-1; i++ {
		ok := true
		tmp, ok = tmp[resPaths[i]].(map[string]interface{})
		if !ok {
			return "", fmt.Errorf("type error, the item {%s} in {%s} is not exist or not a json object", resPaths[i], path)
		}
	}
	res, ok := tmp[resPaths[len(resPaths)-1]].(string)
	if !ok {
		return "", fmt.Errorf("the required field is not a string, raw data: %s", &json)
	}
	return res, nil
}
